﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
using CFCEventReceiver;
using System.Collections.Generic;

namespace CFCEventReceiver.UACEventReceiver
{

    /// <summary>
    /// List Item Events
    /// </summary>
    public class UACEventReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// An item was added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdded(properties);
            Utility.CheckUACConfig(properties);
            Utility.CheckUACListConfig(properties);
            try
            {
                base.EventFiringEnabled = false;
                properties.ListItem.SetItemLevelPermission();
            }
            catch
            {
                throw;
            }
            finally
            {
                base.EventFiringEnabled = true;
            }
        }
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            Utility.DelUACConfig(properties);
            Utility.DelUACListConfig(properties);
            base.ItemDeleting(properties);
        }
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            if (string.Equals("UACConfig", properties.ListTitle, StringComparison.OrdinalIgnoreCase))
            {
                if (properties.ListItem["ListName"].ToString() != properties.AfterProperties["ListName"].ToString())
                {
                    Utility.DelUACConfig(properties);
                }
            }
            base.ItemUpdating(properties);
           
        }
        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            Utility.CheckUACConfig(properties);
            Utility.CheckUACListConfig(properties);
            try
            {
                base.EventFiringEnabled = false;
                properties.ListItem.SetItemLevelPermission();
            }
            catch
            {
                throw;
            }
            finally
            {
                base.EventFiringEnabled = true;
            }
        }
    }
}
